<?php
/*
 * 订单
 */
namespace Admin\Controller;
use Admin\Model\orderModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\moneylogModel;
use Admin\Model\memberModel;
use Admin\Model\expresscomModel;
use Admin\Model\goodsModel;
use Mobile\Controller\PaywechatController;

class OrderController extends BaseController {
    
    public $orderModel;
    public $moneylogMondel;
    public $goodsModel;
    public $fapiaoModel;

    public function __construct() {
        parent::__construct();
        $this->orderModel = new orderModel();
        $this->memberModel = new memberModel();
        $this->moneylogMondel = new moneylogModel();
        $this->goodsModel = new goodsModel();
        $this->fapiaoModel = M('fapiao');
    }
    
    /*
     * 订单状态
     */
    protected function _order_status($order){
        
        $arr[0] = '';
        $arr[1] = '<span class="ordersend" delivery_mobile="'.$order['delivery_mobile'].'" delivery_name="'.$order['delivery_name'].'" orderid="'.$order['order_id'].'"><a class="btn btn-primary vtal-2" style="padding:2px 10px;line-height: 15px;height:15px;">发货</a></span>';
        $arr[2] = '';
        $arr[3] = '<span class="orderback" orderid="'.$order['order_id'].'"><a>确认退款</a></span><!--<p class="noorderback" orderid="'.$order['order_id'].'"><a>拒绝退款</a></p>-->';
        $arr[4] = '';
        $arr[5] = '<span class="ordersend" delivery_mobile="'.$order['delivery_mobile'].'" delivery_name="'.$order['delivery_name'].'" orderid="'.$order['order_id'].'"><a class="btn btn-primary vtal-2" style="padding:2px 10px;line-height: 15px;height:15px;">修改单号</a></span>';
        $arr[6] = '';
        
        if($this->admininfo['role_id'] == 1){
            $tk = '';
            if(true){
                $tk .= '<br><br><a href="javascript:void(0);" class="btn btn-danger vtal-2 orderback" style="padding:2px 10px;line-height: 15px;height:15px;" orderid="'.$order['order_id'].'">退款</a>';
            }
            $arr[1] .= $tk;
            $arr[5] .= $tk;
            $arr[2] .= $tk;
        }
        
        return $arr[$order['checked']]; 
    }
    
    /*
     * 订单状态
     */
    protected function _order_status3($order){
        $arr[0] = '<span class="red">待付款</span>';
        $arr[1] = '<span class="yellow">待发货</span>';
        $arr[2] = '<span class="green">已完成</span>';
        $arr[3] = '<span class="red">待退款</span>';
        $arr[4] = '<span class="gray">已退款</span>';
        $arr[5] = '<span class="green">已发货</span>';
        $arr[6] = '<span class="gray">已关闭</span>';
        return $arr[$order['checked']];
    }
    
    /*
     * 订单状态
     */
    protected function _order_status2($order){
        $arr[0] = '待付款';
        $arr[1] = '待发货';
        $arr[2] = '已成交';
        $arr[3] = '退款中';
        $arr[4] = '已退款';
        $arr[5] = '已发货';
        $arr[6] = '已关闭';
        return $arr[$order['checked']];
    }
    
    
    /*
     * status
     */
    protected function _get_where_status(){
        $data = $_GET;
        $where = '';
        if(isset($data['status'])){
            if($data['status']<7){
                $where = " AND checked=".$data['status'];
            }else if($data['status']==8){
                $where = " AND checked IN (3,4)";
            }
        }
        return $where;
    }
    
    /*
     * 查找条件
     */
    protected function _get_order_where(){

        $arrow = array(
            "order_sn",
            "delivery_name",
            "delivery_mobile",
            "express_no",
            "express",
            "start_create_time",
            "end_create_time",
            "order_user_id",
            "order_id",
            "printed",
            "goods_name",
            "start_send_time",
            "end_send_time",
            "province","city","county"
        );//允许提交的数据
        $data = param_filter($_GET,$arrow,$must=NULL,$filter=true);//过滤数据
        
        $where = "1";
        //todo
        if(is_set($data,'order_sn')){
            $where .= " AND order_sn='".$data['order_sn']."'";
			
        }
        if(is_set($data,'order_id')){
            $where .= " AND order_id='".$data['order_id']."'";
        }
        if(is_set($data,'goods_name')){
			$where .= " AND goods_names LIKE '%".$data['goods_name']."%' ";
		}
        
        if(is_set($data,'order_user_id')){
           $where .= " AND uid='".$data['order_user_id']."'";
        }
        
        if(is_set($data,'delivery_name')){
           $where .= " AND delivery_name='".$data['delivery_name']."'";
        }
        if(is_set($data,'delivery_mobile')){
           $where .= " AND delivery_mobile='".$data['delivery_mobile']."'";
        }
        if(is_set($data,'express_no')){
           $where .= " AND express_no='".$data['express_no']."'";
        }
        if(is_set($data,'express')){
           $where .= " AND express='".$data['express']."'";
        }
        
        if(is_set($data,'start_create_time')){
            $where .= " AND create_time>='".$data['start_create_time']."'";
        }
        if(is_set($data,'end_create_time')){
            $where .= " AND create_time<'".trim($data['end_create_time'])."'";
        }
        if(is_set($data,'start_send_time')){
            $where .= " AND send_time>='".$data['start_send_time']."'";
        }
        if(is_set($data,'end_send_time')){
            $where .= " AND send_time<'".trim($data['end_send_time'])."'";
        }
        
        if(is_set($data,'province')){
            $where .= " AND province='".$data['province']."'";
            $delivery['province'] = $data['province'];
        }
        if(is_set($data,'city') ){
            $where .= " AND city='".$data['city']."'";
            $delivery['city'] = $data['city'];
        }
        if(is_set($data,'county')){
            $where .= " AND county='".$data['county']."'";
            $delivery['county'] = $data['county'];
        }
        $this->assign('delivery',$delivery);

        return $where;
    }
    
    /*
     * 统计数量
     */
    protected function _order_count($where=1){
        
        //全部订单
       //3.待退款 4已退款,5发货,2完成,0未完成,6订单关闭,1已付款 
        $order_count =  array();
        $order_count[0] = $this->orderModel->getOrderCount($where." AND checked=0");//0.未完成
        $order_count[1] = $this->orderModel->getOrderCount($where." AND checked=1");//1.已经付款
        $order_count[2] = $this->orderModel->getOrderCount($where." AND checked=2");//2.已经完成
        $order_count[3] = $this->orderModel->getOrderCount($where." AND checked=3");//3.待退款
        $order_count[4] = $this->orderModel->getOrderCount($where." AND checked=4");//4.已退款
        $order_count[5] = $this->orderModel->getOrderCount($where." AND checked=5");//5.已发货
        $order_count[6] = $this->orderModel->getOrderCount($where." AND checked=6");//6.订单关闭
        $order_count[7] = $this->orderModel->getOrderCount($where);//7.全部订单
        $order_count[8] = $this->orderModel->getOrderCount($where." AND checked IN(3,4)");//8.全部售后订单
        
        $order_count[9] = $this->orderModel->getOrderCount($where." AND checked=5 AND print_nums>0");//8.已经打印
        $order_count[10] = $this->orderModel->getOrderCount($where." AND checked=5 AND print_nums=0");//8.未打印
        
        return $order_count;
    }
    
    /*
     * 订单列表
     */
    public function index(){
        
        if(!isset($_GET['status'])){
            $status = 7;
        }else if(isset($_GET['status']) && !$_GET['status']){
            $status = 0;
        }else{
            $status = $_GET['status'];
        }
        $this->assign('status',$status);
        
        //销售订单
        if(is_set($_GET, 'xiaoshou_user_id')){
            //查找到他的所有一级下线
            $where_xiaoshou = array(
                'refer_uid' => $_GET['xiaoshou_user_id']
            );
            $xiaoshou_uid_lists = $this->memberModel->getMemberLists($where_xiaoshou);
            $xiaoshou_uids = array();
            if(!empty($xiaoshou_uid_lists)){
                foreach($xiaoshou_uid_lists as $k=>$v){
                    $xiaoshou_uids[] = $v['uid'];
                }
            }
            if(!empty($xiaoshou_uids)){
                $xiaoshou_uids_str = implode(",",$xiaoshou_uids);
            }else{
                //无销售
                $this->display();exit;
            }
        }
        
        
        $page = get('p',1);
        $where = $this->_get_order_where();//不带status的查询条件
        if($xiaoshou_uids_str){
            $where .= " AND uid IN(".$xiaoshou_uids_str.") ";
        }
        
        $count = $this->_order_count($where);//统计数量
        
        $where .= $this->_get_where_status();//拼接状态
        
        if(is_set($_GET,'printed') && $_GET['printed']==1){
            $where .= " AND checked=5 AND print_nums>0 ";
        }else if(is_set($_GET,'printed') && $_GET['printed']==2){
            $where .= " AND checked=5 AND print_nums=0 ";
        }
        
       // $order_list = $this->orderModel->where("king_uid = 0")->getOrderList($where,$page);//订单列表
        $order_list = $this->orderModel->getOrderList($where,$page);//订单列表
        if(!empty($order_list)){
            foreach ($order_list as $ok=>$ov){
                $order_status = $this->_order_status($ov);
                $order_status3 = $this->_order_status3($ov);
                $order_list[$ok]['ostatus3'] = $order_status3;
                $order_list[$ok]['ostatus'] = $order_status;
                $order_list[$ok]['delivery'] = unserialize($ov['delivery']);//配送信息
                $order_list[$ok]['goods'] = unserialize($ov['goods']);//订单商品
                if($ov['order_type'] == 1) {
                    $order_list[$ok]['baodan'] = M('member')->where(array('uid'=>$ov['baodan_uid']))->find();
                }
                
                $text = '';
                if($ov['order_type']==1) {
                    $text .= "[报单][报单用户:{$order_list[$ok]['baodan']['nickname']}--ID:{$order_list[$ok]['baodan']['uid']}]";
                }elseif($ov['order_type']==2) {
                    $text .= '[补货]';
                }elseif($ov['order_type']==3) {
                    $text .= '[提货]';
                }elseif($ov['order_type']==4) {
                    $text .= '[充值]';
                }
                if(!$ov['is_delivery']) {
                    $text .= "[虚拟库存无需发货]";
                }
                
                if($ov['action_uid']) {
                    $actionM = M('member')->where(array('uid'=>$ov['action_uid']))->getField('realname');
                    $text .= "操作人：{$actionM}";
                }
                
                $order_list[$ok]['type_text'] = $text;
                    
                switch ($ov['pay_type']){
                    case 1: $pay_typename = '微信支付';break;
                    case 3: $pay_typename = '支付宝支付';break;
                    case 4: $pay_typename = '银行卡支付';break;
                    case 5: $pay_typename = '微信二维码支付';break;
                    case 6: $pay_typename = '后台手工支付';break;
                    case 8: $pay_typename = '通联网银支付';break;
                    default :$pay_typename = '支付';break;
                }
                $order_list[$ok]['pay_typename'] = $pay_typename;
                switch ($ov['order_type']) {
                    case 1: {
                        $order_list[$ok]['order_type_value'] = "[报单]报单人：{$ov['delivery_name']} 报单人手机：{$ov['delivery_mobile']}";
                        break;
                    }
                    case 2: $order_list[$ok]['order_type_value'] = '[复购]';break;
                    case 3: {
                        $xiadanInfo = M('member')->where(array('uid'=>$ov['xiadan_uid']))->find();
                        $order_list[$ok]['order_type_value'] = "[替人下单]下单人：{$xiadanInfo['realname']} 下单人ID：{$xiadanInfo['uid']}";
                        break;
                    }
                }
            }
        }
        $pagecount = $this->orderModel->getOrderCount($where);
        
        $page = new \Think\Page($pagecount, 10);
        $show = $page->show3();
        $this->assign('page', $show); 
        
        //物流公司
        $expresscomModel = new expresscomModel();
        $where_ecom = array(
            "status" => 1
        );
        $expresscom = $expresscomModel->getExpresscomLists($where_ecom);
        $this->assign('expresscom',$expresscom);
        $params = "?order_sn=".get('order_sn')."&order_user_id=".get('order_user_id')
                ."&delivery_name=".get('delivery_name')."&delivery_mobile".get('delivery_mobile')
                ."&start_create_time=".get('start_create_time')
                ."&end_create_time=".get('end_create_time')
                ."&express=".get('express')."&express_no="
                .get('express_no')."&goods_name=".get('goods_name')
                ."&start_send_time=".get('start_send_time')
                ."&end_send_time=".get('end_send_time');
       // $params .= "&king_uid=".$king_uid."&king_realname=".$king_realname;
		
        $params .= "&king_uid=".$king_uid."&king_realname=".$king_realname;
        
        $this->assign('params',$params);
        $this->assign('count',$count);
        $this->assign('datalist',$order_list);
        
      
        $this->display();
    }
    
    
    /*
     * 导出订单
     */
    public function orderexcel(){
        
        if(!isset($_GET['status'])){
            $status = 7;
        }else if(isset($_GET['status']) && !$_GET['status']){
            $status = 0;
        }else{
            $status = $_GET['status'];
        }
        
        //销售订单
        if(is_set($_GET, 'xiaoshou_user_id')){
            //查找到他的所有一级下线
            $where_xiaoshou = array(
                'refer_uid' => $_GET['xiaoshou_user_id']
            );
            $xiaoshou_uid_lists = $this->memberModel->getMemberLists($where_xiaoshou);
            $xiaoshou_uids = array();
            if(!empty($xiaoshou_uid_lists)){
                foreach($xiaoshou_uid_lists as $k=>$v){
                    $xiaoshou_uids[] = $v['uid'];
                }
            }
        
            if(!empty($xiaoshou_uids)){
                $xiaoshou_uids_str = implode(",",$xiaoshou_uids);
            }
        }
        
        $where = $this->_get_order_where();//不带status的查询条件
        
        if($xiaoshou_uids_str){
            $where .= " AND uid IN(".$xiaoshou_uids_str.") ";
        }
        
        $count = $this->_order_count($where);//统计数量
        
        $where .= $this->_get_where_status();//拼接状态
        

        $order_list = $this->orderModel->getOrderLists($where);//订单列表
        
        
        $datastr = "";
        
        if(!empty($order_list)){
            foreach ($order_list as $ok=>$ov){
                $order_status = $this->_order_status2($ov);
                $order_list[$ok]['ostatus'] = $order_status;
        
                $order_list[$ok]['delivery'] = unserialize($ov['delivery']);//配送信息
                $order_list[$ok]['goods'] = unserialize($ov['goods']);//订单商品
                
                $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$order_list[$ok]['nickname']).",";//转义
                
                $datastr .= $order_list[$ok]['uid']."\t".",";//UID
                
                $datastr .= $order_list[$ok]['order_id']."\t".",";//UID
                $datastr .= $order_list[$ok]['order_sn'].",";//UID
                $datastr .= $order_list[$ok]['create_time']."\t".",";//UID
                $datastr .= $order_list[$ok]['pay_time']."\t".",";//UID
                
                $goods = "";
                foreach( $order_list[$ok]['goods'] as $kk=>$val){
                    
                    
                    if($val['guige_name']){
                        $val['goods_name'] = $val['goods_name'].'【'.$val['guige_name'].'】';
                    }
                    $goods .= "名称:".$val['goods_name']." 单价:".$val['shop_price']." 数量:".$val['num']."  ";
                    

                }
                $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$goods).",";//转义
                $datastr .= $order_list[$ok]['pay_orgmoney'].",";//UID
                
                $datastr .= $order_list[$ok]['coupon_money'].",";//红包支付
                $datastr .= $order_list[$ok]['score_money'].",";//微币支付
                $datastr .= $order_list[$ok]['cash_money'].",";//金币支付
                $datastr .= $order_list[$ok]['pay_money'].",";//微信支付
                $datastr .= $order_list[$ok]['yongjin_money'].",";//佣金支付
                $datastr .= $order_list[$ok]['shipping'].",";//运费
                
                
                $datastr .= $order_list[$ok]['ostatus'].",";//UID
                $datastr .= $order_list[$ok]['delivery_name'].",";//UID
                $datastr .= $order_list[$ok]['delivery_mobile']."\t".",";//UID
                $datastr .= $order_list[$ok]['delivery']['wechat_user']."\t".",";//UID
                $address = $order_list[$ok]['delivery']['province']." ".$order_list[$ok]['delivery']['city']." ".$order_list[$ok]['delivery']['county']." ".$order_list[$ok]['delivery']['address'];//收货地址
                 
                $address = str_replace(array(",","'","\""),array("，","＂","＂"),$address);//转义
                
                $datastr .= $address.",";//UID
                
                $hknote = str_replace(array(",","'","\"","\\","\/","`",PHP_EOL," "),"",$order_list[$ok]['khnote']);//转义
                $hknote = str_replace(array("\r\n", "\r", "\n"), "", $hknote);
                $hknote = str_replace(PHP_EOL, '', $hknote);
                
                $datastr .= $hknote.",";//UID
                $datastr .= $order_list[$ok]['express'].",";//UID
                $datastr .= $order_list[$ok]['express_no']."\t,";//UID
                $datastr .= $order_list[$ok]['send_time']."\t,";//UID
                $datastr .= $order_list[$ok]['print_nums']."\t"."\n";//UID
                
            }
        }else{
            return false;
        }
        
        
        
        
        $header = "用户昵称,用户ID,订单ID,订单号,下单时间,付款时间,商品,商品总金额,红包支付,微币支付,金币支付,微信支付,佣金支付,运费,订单状态,收货人,收货人电话,微信号,收货地址,客户备注,物流公司,物流单号,发货时间,快递单打印次数\n";
        
        
        $this->excel($datastr,$header,$excel_name='订单信息-');
        
        
        
        
    }
    
    

    /*
     * 发货
     */
    public function send(){
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        $data =  param_filter($_POST,array('express','express_no','order_id'),array('express','express_no','order_id'),$filter=true,true);//过滤数据
        if(!$data){
            return_json(1,"请正确填写物流信息");
        }
        
        //查找订单信息
        $where = array(
            "order_id" => $data['order_id']
        );
        $order = $this->orderModel->getOrder($where);
        if($order['checked'] != 1 && $order['checked'] != 5){
            return_json(1,"当前订单状态不支持发货,请检查");
        }
        
        //可以发货
        $data['checked'] = 5;
        $data['send_time'] = date("Y-m-d H:i:s");//发送时间
        
        $res = $this->orderModel->editOrder($where, $data);
        if($res){
            
            //发送模板消息
            $msg = $this->_sendmsgtmp($order,$data);//拼接模板消息

            $msgttt = array(
                "uid" => $order['uid'],
                "openid" => $order['openid'],
                "nickname" => $order['nickname'],
                "groupid" => -1,
                "content" => $msg,
                "send_priority" => 1,
                "create_time" => time(),
                "send_time" => time(),
                "status" => -1,
                "send_plan_time" => time()
            );
            $tmpmsgModel = new tmpmsgModel();
            $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
            
            return_json(0,"发货成功");
        }
        return_json(1,"发货失败");
        
    }
    
    /*
     * 拼接模板消息
     */
    protected function _sendmsgtmp($order,$express){
        
        $tmp_id = $this->tmpl['FA_HUO']['tmp_id'];
		$color = $this->tmpl['FA_HUO']['color'];
        
        $url = get_domain()."/mobile/orderdetail/?order_id=".$order['order_id'];
        $footer ='发货日期:'.date("Y-m-d").'\\n\\n'."点击查看详情...";
        $msg = array(
            "touser" => $order['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("您的订单已发货~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($order['order_sn']),//物流单号
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($express['express']),
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($express['express_no']),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        
        return $msg = urldecode(json_encode($msg));
    }
    
    
    /*
     * 拼接模板消息
     * {{first.DATA}}
审核结果：{{keyword1.DATA}}
商品信息：{{keyword2.DATA}}
退货金额：{{keyword3.DATA}}
审核说明：{{keyword4.DATA}}
审核时间：{{keyword5.DATA}}
{{remark.DATA}}
     */
    protected function _tuikuanmsgtmp($order){
    
        $tmp_id = $this->tmpl['TUIHUO_RES']['tmp_id'];
        $color = $this->tmpl['FA_HUO']['color'];
    
        $url = get_domain()."/mobile/orderdetail/?order_id=".$order['order_id'];
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $order['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("你的退款申请已通过~".'\\n'."订单号:".$order['order_sn']),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode("通过"),//物流单号
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($order['order_title']),
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($order['pay_time']),
                    'color' => $color,
                ),
                'keyword4' => array(
                    'value' => urlencode("资金会在三个工作日内原路退回,如有疑问请联系客服"),
                    'color' => $color,
                ),
                'keyword5' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    /*
     * 强制退款
     */
    
    
    /*
     * 同意退款
     */
    public function tuikuan(){
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        $order_id =  get("order_id");
        if(!$order_id){
            return_json(1,"订单信息有误");
        }
        
        //查找订单信息
        $where = array(
            "order_id" => $order_id
        );
        $order = $this->orderModel->getOrder($where);
        
        //0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
        
        
        
        if(!in_array($order['checked'], array(1,2,3,5))){
            return_json(1,"当前订单状态不支持退款,请检查");
        }

        
        if($order['checked'] != 3){
            //管理员主动退款
            if($this->admininfo['role_id'] != 1){
                return_json(1,"抱歉,仅超级管理员才可以在用户未申请退款的情况下主动退款","","/admin/order/index/");
            }
        }
        
        if($this->admininfo['role_id'] != 1){
            return_json(1,"抱歉,仅超级管理员可以操作退款","","/admin/order/index/");
        }
       
        
        //可以退货
        
        if($order['pay_money'] == 0){
            $result_code = "SUCCESS";
        }else if($order['pay_type']==1){
            $wechatpay = new PaywechatController();
         //   $order['order_sn'] .= "_qrpay";
            $params = $wechatpay->getbackParameters($order);
            $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            $result = $wechatpay->curl_post_ssl($url,$params);
            $arr2 = $wechatpay->xmlToArray($result);
            $result_code = isset($arr2['result_code']) ? $arr2['result_code'] : '';
        }else{
            $result_code = "SUCCESS";
        }
        //手工退款
        //没有微信支付，退款都允许
//        $result_code = "SUCCESS";
       
        if($result_code == "SUCCESS"){
            $data['checked'] = 4;
            $res = $this->orderModel->editOrder($where, $data);

            if($res){
                
                //更改商品销量,库存
                $goods_info = unserialize($order['goods']);
                foreach ($goods_info as $k=>$v){
                    //更改商品销量,库存
                    $where_g = array(
                        "goods_id" => $v['goods_id'],
                    );
                    $goods_kucun = array(
                        "sale_real" => array("exp","sale_real-".$goods_info[$k]['num']),
                        //"stock" => array("exp","stock+".$goods_info[$k]['num']),
                        //"sale_all" => array("exp","sale_real+sale_basic"),
                    );
                    $kucun = $this->goodsModel->editGoods($where_g, $goods_kucun);
                }
                
                if($order['sj_gnums']>0){
                    
                    $userinfo = $this->memberModel->where(array("uid"=>$order['uid']))->find();
                    $this->memberModel->where(array("uid"=>$order['uid']))->setDec('jinhuo_nums',$order['sj_gnums']);
                    $c = M("actionlog");
                    $change6['log_type'] = 6;
                    $change6['action_username'] = $this->admininfo["username"];
                    $change6['target_uid'] = $userinfo["uid"];
                    $change6['target_username'] = $userinfo["realname"]?$userinfo["realname"]:$userinfo["nickname"];
                    $change6['from_data'] = $userinfo["jinhuo_nums"];
                    $change6['to_data'] = $userinfo["jinhuo_nums"]-$order['sj_goodsnums'];
                    $change6['content'] = "(退货扣减)".$userinfo["jinhuo_nums"]."盒->".$change6['to_data']."盒";
                    $change6['create_time'] = date('Y-m-d H:i:s');
                    $c->data($change6)->add();
                    
                }
                
                $this->_kouchuYongjin($order);//扣除佣金
                
                //退还支付的佣金,现金,微币,提货币
                $this->_tuiyongjin($order);
                
                //发送模板消息
                $msg = $this->_tuikuanmsgtmp($order);//拼接模板消息
                $msgttt = array(
                    "uid" => $order['uid'],
                    "openid" => $order['openid'],
                    "nickname" => $order['nickname'],
                    "groupid" => -1,
                    "content" => $msg,
                    "send_priority" => 1,
                    "create_time" => time(),
                    "send_time" => time(),
                    "status" => -1,
                    "send_plan_time" => time()
                );
                $tmpmsgModel = new tmpmsgModel();
                $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
            
                return_json(0,"退款成功,已经退还支付的佣金,积分,余额。微信支付部分将原路返回，如有线下交易请人工处理","","/admin/order/index/?status=4");
            }else{
                return_json(1,"退款出现异常");
            }
            
            
        }else{
            return_json(1,"退款失败,失败原因:微信证书错误".$arr2['err_code_des'].$result);
        }

       

        
    }
    
    /*
     * 退还佣金
     */
    protected function _tuiyongjin($order){
        
        $this->_inMoneylog($order['yongjin_money'],$order,1);
        
        $this->_inMoneylog($order['cash_money'],$order,3);
        
        $this->_inMoneylog($order['score_money'],$order,2);
        
        $this->_inMoneylog($order['tihuo_money'],$order,11);
        
        $this->_inMoneylog($order['prize_money'],$order,12);
        
        $this->_inMoneylog($order['ex_cash'],$order,4);
    }
    

    /*
     * 写退还流水
     * $mtype 1分销佣金,2重消币 ,3现金电子币 ,4重消佣金,5互助奖,6车房奖, 7领导奖, 8分红奖 ,9保证金 , 10个税 , 11提货币流水
     */
    protected function _inMoneylog($money,$order,$mtype){
    
        if($money <= 0){
            return false;//金额等于0 不做任何操作
        }
    
        $uid = $order['uid'];
    
        switch($mtype){
            case 2:
                $this->memberModel->jiaQian($uid,'score',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('score')->find();
                $yue = $userinfo['score'];
                break;
            case 3:
                $this->memberModel->jiaQian($uid,'cash_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('cash_money')->find();
                $yue = $userinfo['cash_money'];
                break;
            case 1:
                $this->memberModel->jiaQian($uid,'money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('money')->find();
                $yue = $userinfo['money'];
                break;
            case 11:
                $this->memberModel->jiaQian($uid,'tihuo_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('tihuo_money')->find();
                $yue = $userinfo['tihuo_money'];
                break;
            case 12:
                $this->memberModel->jiaQian($uid,'prize_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('prize_money')->find();
                $yue = $userinfo['prize_money'];
                break;
            case 4:
                $this->memberModel->jiaQian($uid,'ex_cash',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->field('ex_cash')->find();
                $yue = $userinfo['ex_cash'];
                break;
            default:
                return false;
        }
    
        $money_log = array(
            "uid" => $order['uid'],
            "nickname" => $order['realname']?$order['realname']:$order['nickname'],
            "logtype" => 1,//收入 1收入 0支出
            "mtype" => $mtype,//类型
            "money" => $money,
            "content" => "【订单退款】".$order['order_title'],
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['order_cashmoney'],//订单支付的金额(需要分佣的金额)
            "order_nickname" => $order['realname']?$order['realname']:$order['nickname'],
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "un_lock" => 1,//不锁定,立即扣除 1解锁,0锁定
            "manager_username" => $this->admininfo['username'],
            "from_jibie" => 0,
            "cash_money" => $yue,//余额
            "note" => "退款"
        );
        
        $res = $this->moneylogMondel->addMoneylog($money_log);
    
        return $res;
    
    }

    /*
     * 退货扣除相关奖励
     */
    protected function _kouchuYongjin($order){
    
        //写流水
        $moneylogModel = new moneylogModel();
        if(empty($order['order_id'])){
            return false;
        }
        
        $where = array(
            "order_id" => $order['order_id'],
            "logtype" => 1
        );
        $moneylist = $moneylogModel->getMoneylogLists($where);
        if(empty($moneylist)){
            return false;
        }
    
        foreach ($moneylist as $k=>$v){
    
            if(empty($v)){
                continue;
            }
    
            $moneydata = array();//清空
            $data = array();//清空
    
            $data = $v;
            unset($data['log_id']);
            
            $data["content"] = "[订单退款扣除]".$v['content'];
            $data["logtype"] = 0;
            $data["create_time"] = date("Y-m-d H:i:s");
    
    
            $where_uid = array('uid'=>$v['uid']);
            if(!$v['uid']){
                continue;
            }
            
            if($v['mtype'] == 1){
                //佣金
                //写用户金额表
                $money = $v['money'];
                if($money>0){
                    //2016年4月27日20:33:14
                    if($v['un_lock'] == 1){
                        //解锁
                        $res = $this->memberModel->where($where_uid)->setDec("money",$money);
                    }else if($v['un_lock'] == 0){
                        //锁定
                        $res = $this->memberModel->where($where_uid)->setDec("lock_money",$money);
                    }
                
                }else{
                    continue;
                }
                
            }else if($v['mtype'] == 2){
                //积分
                $score = $v['money'];
                if($score>0){
                    $res = $this->memberModel->where($where_uid)->setDec("score",$score);
                }else{
                    continue;
                }
                
            }else if($v['mtype'] == 12){//2017/2/8 奖励佣金
                //佣金
                //写用户金额表
                $money = $v['money'];
                if($money>0){
                    //2016年4月27日20:33:14
                    if($v['un_lock'] == 1){
                        //解锁
                        $res = $this->memberModel->where($where_uid)->setDec("prize_money",$money);
                    }else if($v['un_lock'] == 0){
                        //锁定
                        $res = $this->memberModel->where($where_uid)->setDec("lockprize_money",$money);
                    }
                }else{
                    continue;
                }
                
            }else{
                continue;
            }
    
            $res1 = $moneylogModel->addMoneylog($data);//写流水
            
        }
    
        return true;
    
    }
    
    
    
    
    /*
     * 打印订单
     */
    public function dayin(){
    
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        
        if(!is_set($_GET,'start_create_time') && !is_set($_GET,'order_sn')){
            return_json(1,"请指定订单创建起始时间");
        }

    
        //销售订单
        if(is_set($_GET, 'xiaoshou_user_id')){
            //查找到他的所有一级下线
            $where_xiaoshou = array(
                'refer_uid' => $_GET['xiaoshou_user_id']
            );
            $xiaoshou_uid_lists = $this->memberModel->getMemberLists($where_xiaoshou);
            $xiaoshou_uids = array();
            if(!empty($xiaoshou_uid_lists)){
                foreach($xiaoshou_uid_lists as $k=>$v){
                    $xiaoshou_uids[] = $v['uid'];
                }
            }
    
            if(!empty($xiaoshou_uids)){
                $xiaoshou_uids_str = implode(",",$xiaoshou_uids);
            }
    
        }
    
        $where = $this->_get_order_where();//不带status的查询条件
    
        if($xiaoshou_uids_str){
            $where .= " AND uid IN(".$xiaoshou_uids_str.")";
        }
    
        //状态为已发货
        $where .= " AND checked IN(1)";
    
        $order_list = $this->orderModel->getOrderLists($where);//订单列表
    
        $where .= " AND print_nums>=1";
    
        $printed_nums = $this->orderModel->getOrderCount($where);//已经打印的订单数量
    
    
        if(empty($order_list)){
            return_json(1,"没有需要打印的订单,请先搜索出需要打印的订单");
        }
    
        $dayin = array();
        foreach ($order_list as $ok=>$ov){
    
            $order_list[$ok]['delivery'] = unserialize($ov['delivery']);//配送信息
            $order_list[$ok]['goods'] = unserialize($ov['goods']);//订单商品
    
            $nickname = str_replace(array(",","'","\""),array("，","＂","＂"),$order_list[$ok]['nickname']);//转义
    
            $dayin[$ok]['nickname'] = $nickname;//用户昵称
    
            $dayin[$ok]['uid'] = $order_list[$ok]['uid'];//用户编号
    
            $dayin[$ok]['order_id'] = $order_list[$ok]['order_id'].",";//订单编号
    
            $goods = "";
            foreach( $order_list[$ok]['goods'] as $kk=>$val){
                $goods .= "名称:".$val['goods_name']." 数量:".$val['num']." ";
            }
            $goods = str_replace(array(",","'","\""),array("，","＂","＂"),$goods)."。";//转义
    
            //商品
            $dayin[$ok]['goods'] = $goods;//
    
            //收货人
            $dayin[$ok]['delivery_name'] = $order_list[$ok]['delivery_name'];//
    
            //手机号
            $dayin[$ok]['delivery_mobile'] = $order_list[$ok]['delivery_mobile'];//
    
            //详细收货地址
            $address = " ".$order_list[$ok]['delivery']['address'];//收货地址
             
            $address = str_replace(array(",","'","\""),array("，","＂","＂"),$address);//转义
    
            $dayin[$ok]['address_datouzi'] = $order_list[$ok]['delivery']['province']." ".$order_list[$ok]['delivery']['city']." ".$order_list[$ok]['delivery']['county'];
    
            $dayin[$ok]['address_detail'] = $address;
    
            $dayin[$ok]['khnote'] = $order_list[$ok]['khnote'];//UID
            
            $dayin[$ok]['print_nums'] = $order_list[$ok]['print_nums']+1;//UID
    
            $dayin[$ok]['express'] = $order_list[$ok]['express'];//物流公司
    
            $dayin[$ok]['express_no'] = $order_list[$ok]['express_no'];//物流单号
    
            if($dayin[$ok]['express'] == "中通快递"){
                $dayin[$ok]['express_logo'] = $order_list[$ok]['express_no'];//快递公司logo
            }
    
        }
    
        $pdata = array(
            "dayin" => $dayin,
            "all_nums" => count($dayin),
            "printed_nums" => $printed_nums,
        );
    
        if($printed_nums){
            $msg = "即将打印".$pdata['all_nums']."个面单,其中包含已经打印过的订单".$printed_nums."个,是否继续打印?";
        }else{
            $msg = "即将打印".$pdata['all_nums']."个面单,是否继续打印?";
        }
    
        return_json(0,$msg,$pdata);
    
    }
    
    
    /*
     * 更改打印次数
     */
    public function dayinnums(){
        $order_ids = post("order_ids");
        if(!empty($order_ids) && is_array($order_ids)){
            $where = array(
                "order_id" => array("IN",$order_ids)
            );
            $res = $this->orderModel->where($where)->setInc('print_nums');
            
        }
        return_json(0);
    }
    
    
    /*
     * 批量发货
     */
    public function excelfahuo(){
        //获取上传文件路径信息，pathinfo()以数组的形式返回文件的路径信息
        
        $destination = ROOT."/cache/csv/".time().".csv";
        
        move_uploaded_file($_FILES['imgFile']['tmp_name'], $destination);
        
        checkBOM($destination);
        
        $file = fopen($destination,"r");

        $goods_list = array();
        while ($data = fgetcsv($file)) { 
            //每次读取CSV里面的一行内容           
            //print_r($data); //此为一个数组，要获得每一个数据，访问数组下标即可
            $goods_list[] = $data;
        }
        fclose($file);
        
        if(empty($goods_list)){
            return_json(1,"没有发现有效数据");
        }
        
        $order_id_key = $order_company_key = $order_danhao_key = -1;
        foreach($goods_list[0] as $kk=>$vv){
            if($vv == "订单ID"){
                $order_id_key = $kk;
                continue;
            }
            if($vv == "物流公司"){
                $order_company_key = $kk;
                continue;
            }
            if($vv == "物流单号"){
                $order_danhao_key = $kk;
                continue;
            }
        }
        
        if($order_id_key<0 || $order_company_key<0 || $order_danhao_key<0){
            
            return_json(1,"发货失败,上传的文件内容格式错误");
        }
        
        unset($goods_list[0]);
        
        $all = $active = 0;
        
        foreach($goods_list as $k=>$v){
            
            $order_id = trim($v[$order_id_key]);
            $order_id = str_replace(array(",","'","\"","\\","\/","`"),array("","","","","",""),$order_id);//转义
            $order_id = intval($order_id);
            
            if(!$order_id){
                continue;
            }
            $where = array(
                "order_id" => $order_id
            );
            
            $all++;
            
            //查找订单信息
            $order = $this->orderModel->getOrder($where);
            if(empty($order)){
                continue;
            }
            //0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
            if($order['checked'] != 1 && $order['checked'] != 5){
                continue;
            }
            
            $wuliu = trim($v[$order_company_key]);
            $wuliu = str_replace(array(",","'","\"","\\","\/","`"),array("","","","","",""),$wuliu);//转义
            
            $sn = trim($v[$order_danhao_key]);
            $sn = str_replace(array(",","'","\"","\\","\/","`"),array("","","","","",""),$sn);//转义
       
            if(empty($sn) || empty($wuliu)){
                continue;
            }
            
            
            $data = array(
                "express" => $wuliu,
                "express_no" => $sn,
                "send_time" => date("Y-m-d H:i:s"),
                "checked" => 5,
                "order_id" => $order_id
                
            );

            //发货
            $res = $this->orderModel->editOrder($where, $data);
            if(!$res){
                continue;
            }
                

            //发送模板消息
            $msg = $this->_sendmsgtmp($order,$data);//拼接模板消息
        
            $msgttt = array(
                "uid" => $order['uid'],
                "openid" => $order['openid'],
                "nickname" => $order['nickname'],
                "groupid" => -1,
                "content" => $msg,
                "send_priority" => 1,
                "create_time" => time(),
                "send_time" => time(),
                "status" => -1,
                "send_plan_time" => time()
            );
            $tmpmsgModel = new tmpmsgModel();
            $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列

            $active++;

        }
        
        $msg = "总共记录".$all."条,成功发货".$active."条";
        
        return_json(0,$msg,"","/admin/order/index/status/5");

    }
    public function tongji(){
            $allow = array(
                'start_create_time','end_create_time','province','city','county','start_pay_time','end_pay_time'
                );
            $data = param_filter($_GET, $allow);

            $data["date"] = "统计销量";

            $g = M('goods');
            $goodslist = $g->where(array('ischeck'=>1))->select();		
            $o = M('order');
            $where = "(checked = 1 OR checked = 2 OR checked = 5)";
            if($data['start_create_time']){
                $where .= " AND send_time>='".$data['start_create_time']."'";
            }
            if($data['end_create_time']){
                $where .= " AND send_time<='".$data['end_create_time']."'";
            }

            if($data['end_pay_time']){
                $where .= " AND pay_time<='".$data['end_pay_time']."'";
            }

            if($data['start_pay_time']){
                $where .= " AND pay_time>='".$data['start_pay_time']."'";
            }

            if($data['province']) {
                $where .= " AND province='".$data['province']."'";
                $delivery['province'] = $data['province'];
            }
            if($data['city']) {
                $where .= " AND city='".$data['city']."'";
                $delivery['city'] = $data['city'];
            }
            if($data['county']) {
                $where .= " AND county='".$data['county']."'";
                $delivery['county'] = $data['county'];
            }


            $this->assign('delivery',$delivery);

            $orders = $o->where($where)->select();
            foreach($goodslist as $k=>$goods){
                    $index = $k;
                    $goods_id = $goods["goods_id"];
                    foreach($orders as $order){
                            $sale_arr = explode(";",$order["goods_sale"]);
                            foreach($sale_arr as $sale){
                                    $sale = explode(",",$sale);
                                    if($goods_id == $sale[0]){
                                            $goodslist[$index]["salenum"] += $sale[1];
                                    }

                            }
                    }
            }


            $this->assign("goodslist",$goodslist);
            $this->assign("data",$data);
            $this->assign("status",100);
            $this->display();
    }
    /*
     * 皇冠发货的订单页面，只做展示不能发货
     */
    public function kingorder(){


        if(!isset($_GET['status'])){
            $status = 7;
        }else if(isset($_GET['status']) && !$_GET['status']){
            $status = 0;
        }else{
            $status = $_GET['status'];
        }
        $this->assign('status',$status);

        //销售订单
        if(is_set($_GET, 'xiaoshou_user_id')){
            //查找到他的所有一级下线
            $where_xiaoshou = array(
                'refer_uid' => $_GET['xiaoshou_user_id']
            );
            $xiaoshou_uid_lists = $this->memberModel->getMemberLists($where_xiaoshou);
            $xiaoshou_uids = array();
            if(!empty($xiaoshou_uid_lists)){
                foreach($xiaoshou_uid_lists as $k=>$v){
                    $xiaoshou_uids[] = $v['uid'];
                }
            }

            if(!empty($xiaoshou_uids)){
                $xiaoshou_uids_str = implode(",",$xiaoshou_uids);
            }else{
                //无销售
                $this->display();exit;

            }

        }


        $page = get('p',1);
        $where = $this->_get_order_where();//不带status的查询条件
        if($xiaoshou_uids_str){
            $where .= " AND uid IN(".$xiaoshou_uids_str.") ";
        }


        //根据皇冠信息查询
        $king_uid = get('king_uid');
        $king_realname = get('king_realname');
        if($king_uid){
            $where .= " AND king_uid = '".$king_uid."'";
        }
        if($king_realname){
            $where .= " AND king_realname like '%".$king_realname."%'";
        }



        $count = $this->_order_count($where);//统计数量

        $where .= $this->_get_where_status();//拼接状态

        if(is_set($_GET,'printed') && $_GET['printed']==1){
            $where .= " AND checked=5 AND print_nums>0 ";
        }else if(is_set($_GET,'printed') && $_GET['printed']==2){
            $where .= " AND checked=5 AND print_nums=0 ";
        }

        $order_list = $this->orderModel->where("kinguid != 0")->getOrderList($where,$page);//订单列表

        if(!empty($order_list)){
            foreach ($order_list as $ok=>$ov){
                $order_status = $this->_order_status($ov);

                $order_status3 = $this->_order_status3($ov);
                $order_list[$ok]['ostatus3'] = $order_status3;

                $order_list[$ok]['ostatus'] = $order_status;

                $order_list[$ok]['delivery'] = unserialize($ov['delivery']);//配送信息
                $order_list[$ok]['goods'] = unserialize($ov['goods']);//订单商品

            }
        }
        $pagecount = $this->orderModel->getOrderCount($where);

        $page = new \Think\Page($pagecount, 10);
        $show = $page->show3();
        $this->assign('page', $show);

        //物流公司
        $expresscomModel = new expresscomModel();
        $where_ecom = array(
            "status" => 1
        );
        $expresscom = $expresscomModel->getExpresscomLists($where_ecom);
        $this->assign('expresscom',$expresscom);


        $params = "?order_sn=".get('order_sn')."&delivery_name=".get('delivery_name')."&delivery_mobile".get('delivery_mobile')."&start_create_time=".get('start_create_time')."&end_create_time=".get('end_create_time')."&express=".get('express')."&express_no=".get('express_no')."&goods_name=".get('goods_name');
        $params .= "&king_uid=".$king_uid."&king_realname=".$king_realname;

        $this->assign('params',$params);
        $this->assign('count',$count);
        $this->assign('datalist',$order_list);
        $this->assign('action','kingorder');


        $this->display();

    }

    /*
     * 获取物流信息
     */
    protected function _get_wuliuinfo($express_no,$express){
        //0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
        //查询快递信息

        $data['wuliu_status'] = '';
        $data['wuliu_res'] = '';

        $elong = strlen($express_no);
        if($elong>6){
            //查询物流信息
            $wuliu = wuliu($express_no, $express);
            //http://www.aikuaidi.cn/api/

            $status = array(
                0 => '<span style="color:red;">无记录</span>',
                1 => '<span style="color:red;">未录单</span>',
                2 => '<span style="color:green;">在途中</span>',
                3 => '<span style="color:green;">派送中</span>',
                4 => '<span style="color:green;">已签收</span>',
                5 => '<span style="color:red;">拒收</span>',
                6 => '<span style="color:red;">疑难件</span>',
                7 => '<span style="color:red;">退回</span>',
            );

            $status = $status[$wuliu['status']];//结果状态
            $data['wuliu_status'] = $status;

            if($wuliu['errCode'] == 0){
                $data['wuliu_res'] = $wuliu['data'];
            }
        }

        return $data;
    }

    public function wuliuajax(){
        $express_no = get("express_no");
        $express = get("express");
        $res = $this->_get_wuliuinfo($express_no,$express);
        return_json(0,"正在获取物流信息...",$res);
    }


    public function changeorder() {

        if(!IS_AJAX){
            return_json(1,'修改失败,提交方式有误','','/admin/order');
        }

        $id = get('id');
        $order = $this->orderModel->where(array('order_id'=>$id))->find();


        if(empty($order)){
            return_json(1,'修改失败,订单信息不存在','','/admin/order');
        }

        $option['baodan'] = true;
        $callback = new \Mobile\Controller\OrdercallbackController($option);
        $res = $callback->adminChangeOrder($order);
        if(!$res){
            return_json(1,'修改失败','','/admin/order');
        }
        return_json(0,'修改成功','','/admin/order');

    }
	
    public function fapiao () {
        $p = get('p',1);
        $size = 10;
        $list = $this->fapiaoModel->order('id DESC')->page($p,$size)->select();
        $count = $this->fapiaoModel->count();
        $page = new \Think\Page($count, $size);
        $show = $page->show3();
        $this->assign('page',$show);
        $this->assign('datalist',$list);
        $this->display();
    }
    
    public function setexpress () {
        $allow = array(
            'id','express','express_no'
        );
        $data = param_filter($_POST, $allow, $allow, false, true);
        if(empty($data)) {
            return_json(1,'请填写完整');
        }
        $res = $this->fapiaoModel->where(array('id'=>$data['id']))->save($data);
        if($res) {
            return_json(0,'保存成功');
        }
    }
    
}